package qf.hsw.testadmin.controller;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import qf.hsw.testadmin.entity.SysUser;
import qf.hsw.testadmin.service.UserService;
import qf.hsw.util.JwtUtils;
import qf.hsw.util.R;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Objects;

@RestController
@RequestMapping("/sys")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/user/login")
    public R login(@RequestBody SysUser sysUser) {
        // 1. 查询用户
        SysUser dbUser = userService.SelectUserByName(sysUser.getUserName());

        // 2. 检查用户是否存在
        if (dbUser == null) {
            log.warn("登录失败: 用户名 {} 不存在", sysUser.getUserName());
            return R.fail("用户名或密码错误"); // 模糊提示，避免暴露用户信息
        }

        // 3. 验证密码（实际应用中应使用加密比对）
        if (!Objects.equals(sysUser.getPassword(), dbUser.getPassword())) {
            log.warn("用户 {} 密码错误", sysUser.getUserName());
            return R.fail("用户名或密码错误");
        }

        // 4. 生成JWT
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", dbUser.getUserId());
        claims.put("userName", dbUser.getUserName());

        String jwt = JwtUtils.createJwt(claims);
        log.info("用户 {} 登录成功，生成JWT", sysUser.getUserName());

        return R.ok(jwt);
    }

    @GetMapping("user/info")
    public R getInfo(@RequestParam(value = "token") String token) {
        log.info("token:{}", token);
        Claims claims = JwtUtils.parseJWT(token);
        log.info("claims:{}", claims);
//        HashMap<String, Object> claims = (HashMap<String, Object>) JwtUtils.parseJWT(token);
//        Long userId = (Long) claims.get("userId");
        Object userId = claims.get("userId");
        SysUser sysUser = userService.SelectUserById(Long.parseLong(userId.toString()));
        return R.ok(sysUser);
    }

    /**
     * 退出登录
     */
    @PostMapping("user/logout")
    public R logout(HttpSession session) {
        session.invalidate();
        return R.ok();
    }

    @PostMapping("user/register")
    public R Register(@RequestBody SysUser sysUser) {
        SysUser sysUser1 = userService.SelectUserByName(sysUser.getUserName());
        if (sysUser1 != null) {
            return R.fail("用户已存在");
        }
        int insert = userService.insert(sysUser);
        if (insert > 0) {
            return R.ok();
        }
        return R.fail("注册失败");
    }

    @GetMapping("user/selectUserByName")
    public R selectUserByName(String userName) {
        SysUser sysUser = userService.SelectUserByName(userName);
        return R.ok(sysUser);
    }

    @GetMapping("user/selectUserById")
    public R selectUserById(Long userId) {
        SysUser sysUser = userService.SelectUserById(userId);
        return R.ok(sysUser);
    }


}
